import requests
import re
import json
import os
from urllib import parse
import cv2
from PIL import Image


class BaiduPhoto():

    def __init__(self, name, partition, page, size="3"):

        self.name = name
        self.dir_name = "{}:\\{}".format(partition, name)
        os.mkdir(self.dir_name)
        self.img_url_list = []
        self.get_url(page=page, size=size)
        self.download_img()

    def get_url(self, page=5, size="3"):
        """
        每页30张，搜索page页
        图片尺寸 z :  全部：0  特大尺寸： 9 大尺寸 ： 3  中尺寸 ： 2
        """
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0'
        }
        url_name = parse.quote(self.name)
        for i in range(0, page):
            data = "tn=resultjson_com&logid=10787158356478644495&ipn=rj&ct=201326592&is=&fp=result&fr=&word={}&queryWord={}&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z={}&ic=0&hd=&latest=&copyright=&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&expermode=&nojc=&isAsync=&pn={}&rn=30&gsm=1e0000000000001e&1664369110120=".format(
                url_name, url_name, size, str(i * 30))
            url = "https://image.baidu.com/search/acjson?"

            response = requests.get(url + data, headers=headers)

            # print(response.text)
            text = response.text
            # text_dict = json.loads(text)
            compile_str = re.compile('"thumbURL":"(.+?)"')
            compile_list = re.findall(compile_str, text)
            self.img_url_list.extend(compile_list)
        print(len(self.img_url_list))
        return True

    def download_img(self):
        print("开始下载图片.....！")
        for index, img_url in enumerate(self.img_url_list):
            try:
                img_format = re.search("f=.+\?", img_url).group(0)
                img_format = img_format.replace("f=", "").replace("?", "")
                pic = requests.get(img_url, timeout=15)
            except Exception as e:
                print(e)
                continue
            else:
                name = self.dir_name + os.sep + self.name + str(index) + "." + img_format
                fp = open(name, 'wb')
                fp.write(pic.content)
                fp.close()
                print("下载图片...%s" % (name))

        print("下载图片....done !")
        return True


class videoFrame():

    def __init__(self):
        pass

    def video2images(self, Video_Dir, image_Dir, frameInterval=5):
        print("start convert video to  images")
        cap = cv2.VideoCapture(Video_Dir)
        c = 0  # 帧数起点
        index = 1  # 图片命名起点，如1.jpg

        if not cap.isOpened():
            print("Cannot open camera")
            exit()
        fps = cap.get(5)  # get 常用值请百度
        print("当前视频的帧速率为： %s   FPS" % fps)
        frame_count = cap.get(7)
        seconds = int(frame_count / fps)
        print("视频总时长  约为： %d  秒" % (seconds))

        while True:
            # 逐帧捕获
            ret, frame = cap.read()
            # 如果正确读取帧，ret为True
            if not ret:
                print("Can't receive frame.")
                break
            # 设置每 frameInterval 帧取一次图片，若想逐帧抽取图片，可设置c % 1 == 0
            if c % frameInterval == 0:
                # 图片存放路径，即图片文件夹路径
                cv2.imwrite(image_Dir + str(index) + '.jpg', frame)
                index += 1
            c += 1
            cv2.waitKey(1)
            # 按键停止
            if cv2.waitKey(1) == ord('q'):
                break
        print("convert video to  images   done ! ")
        cap.release()

    def images2Video(self, Video_Dir, image_Dir, fps=30,codec="MP4V"):
        """
        *'MJPG'  对应 avi
        *‘MP4V’  对应MP4
        """
        print("start convert to video  !!!")
        ims_path_list = os.listdir(image_Dir)

        def sortname(name):
            true_name = int(name.split(".")[0])
            return true_name

        ims_path_list.sort(key=sortname)

        im_path = os.path.join(image_Dir, ims_path_list[0])
        im_size = Image.open(os.path.join(image_Dir, ims_path_list[0])).size
        fourcc = cv2.VideoWriter_fourcc(*codec)
        videoWriter = cv2.VideoWriter(Video_Dir, fourcc, fps, im_size)

        for i, im_name in enumerate(ims_path_list):
            im_path = os.path.join(image_Dir, im_name)
            frame = cv2.imread(im_path)
            videoWriter.write(frame)

        videoWriter.release()
        print('finish convert to video  !!!')

    def compress_video(self,Video_Dir,out_dir,):
        """ffmpeg"""


if __name__ == "__main__":
    # item = BaiduPhoto(name="黄渤", partition="d", page=5, size="3")
    aaa = videoFrame()
    # aaa.video2images(Video_Dir=r"D:/video/test.mp4", image_Dir=r"D:/images/", frameInterval=1)
    aaa.images2Video(Video_Dir="D:/video/test2.mp4", image_Dir="D:/images/", fps=24,codec="MP4V")
